const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const compression = require('compression');
require('dotenv').config();

const logger = require('./utils/logger');
const externalRoutes = require('./routes/external');
const internalRoutes = require('./routes/internal');
const schedulerRoutes = require('./routes/scheduler');
const schedulerService = require('./services/schedulerService');
const errorHandler = require('./middleware/errorHandler');
const database = require('./config/database');

const app = express();
const PORT = process.env.PORT || 2000;

// 全局错误处理
process.on('uncaughtException', (error) => {
  console.error('未捕获的异常:', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的 Promise 拒绝:', reason);
  process.exit(1);
});

// 安全中间件
app.use(helmet());

// CORS配置
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
  credentials: true
}));

// 请求日志
app.use(morgan('combined'));

// 压缩响应
app.use(compression());

// 解析JSON请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({ 
    status: 'OK', 
    timestamp: new Date().toISOString(),
    version: process.env.npm_package_version || '1.0.0'
  });
});

// 路由
app.use('/api/external', externalRoutes);
app.use('/api/internal', internalRoutes);
app.use('/api/scheduler', schedulerRoutes);

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({ error: '接口不存在' });
});

// 错误处理中间件
app.use(errorHandler.errorHandler);

// 启动服务器
app.listen(PORT, async () => {
  logger.info(`🚀 项目服务已启动，端口: ${PORT}`);
  
  // 测试数据库连接
  try {
    await database.testConnection();
    logger.info('✅ MySQL数据库连接成功');
  } catch (error) {
    logger.error('❌ MySQL数据库连接失败', { error: error.message });
  }
  
  // 启动定时任务调度器
  setTimeout(() => {
    try {
      // 暂时注释掉定时任务调度器启动，避免崩溃
      schedulerService.startTask();
      logger.info('✅ 定时任务调度器启动成功');
    } catch (error) {
      logger.error('❌ 定时任务调度器启动失败', { error: error.message });
    }
  }, 2000); // 延迟2秒启动，确保服务完全启动
});

// 优雅关闭
process.on('SIGTERM', async () => {
  logger.info('收到SIGTERM信号，准备关闭服务...');
  await database.closePool();
  process.exit(0);
});

process.on('SIGINT', async () => {
  logger.info('收到SIGINT信号，准备关闭服务...');
  await database.closePool();
  process.exit(0);
});

module.exports = app;
